package com.example.enews.utils

import android.os.AsyncTask
import android.util.Log
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.util.*
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

object NtpTimeHelper {
    private const val TAG = "NtpTimeHelper"
    private const val NTP_SERVER = "time.google.com" // 使用Google的公共NTP服务器

    // 获取网络时间（返回UTC时间）
    suspend fun getNetworkTime(): Long = suspendCoroutine { continuation ->
        object : AsyncTask<Void, Void, Long>() {
            override fun doInBackground(vararg params: Void?): Long {
                try {
                    val address = InetAddress.getByName(NTP_SERVER)
                    val ntpTime = SimpleNTPClient().requestTime(address, 80)
                    continuation.resume(ntpTime)
                    return ntpTime
                } catch (e: Exception) {
                    Log.e(TAG, "Failed to get network time", e)
                    continuation.resume(System.currentTimeMillis()) // 如果失败则返回本地时间
                    return System.currentTimeMillis()
                }
            }
        }.execute()
    }

    // 简单的NTP客户端实现
    private class SimpleNTPClient {
        fun requestTime(address: InetAddress, port: Int): Long {
            val socket = DatagramSocket(port)
            socket.soTimeout = 5000
            socket.connect(address, port)

            val buffer = ByteArray(48)
            buffer[0] = 0x1B // LI=0, VN=3, Mode=3

            val request = DatagramPacket(buffer, buffer.size)
            socket.send(request)

            val response = DatagramPacket(buffer, buffer.size)
            socket.receive(response)

            // 解析时间戳（前 8 字节）
            var seconds = 0L
            for (i in 0..7) {
                seconds = (seconds shl 8) or (buffer[i].toInt() and 0xFF).toLong()
            }

            // 转换为 Unix 时间戳（毫秒）
            return (seconds - 2208988800L) * 1000
        }
    }

}
